package io.gitee.zhangbinhub.admin.gateway.conf

import io.gitee.zhangbinhub.acp.core.common.CommonTools
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties
import org.springframework.boot.autoconfigure.web.ServerProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.Customizer
import org.springframework.security.config.web.server.ServerHttpSecurity
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers

@Configuration
class GatewayServerAutoConfiguration(
    serverProperties: ServerProperties,
    private val webEndpointProperties: WebEndpointProperties
) {
    private var contextPath: String? = null

    init {
        contextPath = if (CommonTools.isNullStr(serverProperties.servlet.contextPath)) {
            ""
        } else {
            serverProperties.servlet.contextPath
        }
    }

    /**
     * http 验证策略配置
     *
     * @param http http 安全验证对象
     */
    @Bean
    fun actuatorSecurityFilter(http: ServerHttpSecurity): SecurityWebFilterChain {
        http.csrf { it.disable() }
            .securityMatcher(
                ServerWebExchangeMatchers.pathMatchers(
                    "$contextPath${webEndpointProperties.basePath}",
                    "$contextPath${webEndpointProperties.basePath}/**"
                )
            )
            .authorizeExchange { it.anyExchange().authenticated() }
            .httpBasic(Customizer.withDefaults())
        return http.build()
    }
}
